import os
import ffmpeg
import logging

# 音频分离 提取MP4文件的音频 以MP3文件保存
def extract_audio(video_file, audio_file, output_dir):

    try:
        # 提取音频流
        stream = ffmpeg.input(video_file)
        stream = ffmpeg.output(stream, os.path.join(output_dir, audio_file), acodec='libmp3lame',y="-y")
        ffmpeg.run(stream)
        logging.info(f"audio file  {audio_file} generated")
        return True

    except ffmpeg._run.Error:
        logging.warning("Silent audio or other errors")
        return False

# 音频合并 将一个MP3文件和一个 MP4文件合并成一个MP4文件
def merge_audio(video_file, audio_file, output_file):

    try:
        # 提取视频流
        video_stream = ffmpeg.input(video_file)
        # 提取音频流
        audio_stream = ffmpeg.input(audio_file)
        # 合并流
        stream = ffmpeg.output(video_stream, audio_stream, output_file, vcodec='copy', acodec='copy',y="-y")
        ffmpeg.run(stream)
        logging.info(f"file {output_file} generated")

    except ffmpeg._run.Error:
        logging.warning("Merge failed or other error")